<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div>
      <el-table :data="tableData" :row-style="{ height: '77px' }" border style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;font-size: 15px;">
        <el-table-column prop="id" label="ID" width="100"/>
        <el-table-column prop="name" label="名称" width="350"/>
        <el-table-column prop="turnUrl" label="跳转地址" width="350"/>
        <el-table-column prop="bgUrl" label="背景图片" width="auto">
          <template #default="scope">
            <img v-if="scope.row.bgUrl" :src="scope.row.bgUrl" width="50" style="max-height: 90px" alt="photo"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="170">
          <template v-slot="scope">
            <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog :close-on-click-modal="false" v-model="operationItemDialog" title="操作" width="700">
      <el-form :model="form" :rules="rules" ref="form" label-position="right" class="demo-roleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" class="input-size" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="跳转地址" prop="turnUrl">
          <el-input v-model="form.turnUrl" class="input-size" placeholder="跳转地址"></el-input>
        </el-form-item>
        <el-form-item label="背景图片" prop="bgUrl">
          <el-upload
              :before-upload="checkFileType"
              class="avatar-uploader"
              :action="'/api/files/upload'"
              :on-success="photoHandleSuccess"
              :on-error="photoHandleError"
              :show-file-list="false"
          >
            <template #tip>
              <div class="el-upload__tip">
                {{ photoType() }}文件应小于{{ fileSizeLimit() }}
              </div>
            </template>
            <img width="100" height="100" v-if="form.bgUrl" :src="form.bgUrl" class="avatar">
            <img width="100" height="100" v-else>
            <button v-if="form.bgUrl" class="delete-btn" @click="deleteImage">x</button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button style="font-size: 12px" type="primary" @click="submitForm('form')">提交</el-button>
          <el-button style="font-size: 12px;color: #606266" @click="reset('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import Breadcrumb from "@/components/Breadcrumb.vue";
import {fileSizeLimit, photoType} from "@/assets/globalJS.js";

export default {
  name: "HomeSetting",
  components: {Breadcrumb},
  data() {
    return{
      operationItemDialog: false,
      tableData:[],
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        // turnUrl: [
        //   {required: true, message: '请输入跳转地址', trigger: 'blur'},
        // ]
      },
      form:{},
      userInformation:JSON.parse(localStorage.getItem("user")),
      menuOperations:[],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      defaultCheckedKeys: [] // 要在初始化时选中的节点ID
    }
  },
  created() {
    this.load()
  },
  methods: {
    photoType() {
      return photoType
    },
    fileSizeLimit() {
      return fileSizeLimit
    },
    photoHandleError(){
      this.$message.error("上传文件大小请勿超过"+fileSizeLimit)
    },
    // 添加
    addItem(){
      this.operationItemDialog = true;
    },
    // 编辑
    async editItem(scope) {
      Object.assign(this.form, scope)
      this.operationItemDialog = true
    },
    // 提交
    submitForm(val){
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/home-bg-url/edit",this.form).then(res=>{
            if (res.code==='200'){
              this.operationItemDialog=false
              this.$message({
                message:"成功",
                type:"success"
              })
              this.load()
            }else {
              this.$message.error("操作失败"+res.msg)
            }
          })
        }
      })
    },
    deleteImage() {
      this.form.bgUrl = '';
    },
    load(){
      this.form = {}
      request.get("/home-bg-url/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize).then(res => {
        if (res.code === '200') {
          for (let key in res.data) {
            if (key === "records") {
              this.tableData = res.data[key];
            } else if (key === "total") {
              this.total = res.data[key];
            }
          }
        } else {
          this.$message.error("错误"+res.msg)
        }
      })
    },
    // 取消
    reset(val){
      this.operationItemDialog = false;
      this.form={};
      this.$refs[val].resetFields();
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    checkFileType(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      // '.xbm','.tif','pjp','.svgz','jpg','jpeg','ico','tiff','.gif','svg','.jfif','.webp','.png','.bmp','pjpeg','.avif'
      if (
          fileType === '.xbm' ||
          fileType === '.tif' ||
          fileType === '.pjp' ||
          fileType === '.svgz' ||
          fileType === '.jpg' ||
          fileType === '.jpeg' ||
          fileType === '.ico' ||
          fileType === '.tiff' ||
          fileType === '.gif' ||
          fileType === '.svg' ||
          fileType === '.jfif' ||
          fileType === '.webp' ||
          fileType === '.png' ||
          fileType === '.bmp' ||
          fileType === '.pjpeg' ||
          fileType === '.avif'
      ) {
        // 不处理
      } else {
        this.$message.error(
            '不是常用图片格式文件,请上传正确的图片类型'
        )
        return false
      }
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
    // photo上传
    photoHandleSuccess(response) {
      this.form.bgUrl=`/api/file/download${response}`
    },
  }
}
</script>

<style scoped>
:deep(.el-table th .cell)  {
  font-weight: 700
}
:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 700
}
.input-size {
  font-size: 13px;
}
.avatar-uploader .el-upload {
  border: 1px black var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 29px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader{
  position: relative;
  display: inline-block;
}
.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  color: black;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 17px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
</style>
